﻿using CSCSN.EntitiyModels;
using CSCSN.EntitiyModels.ApplicationTaskAbout;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSCSN.ORM
{
    public class SeedData
    {
        #region 新增用户、角色功能
        private static UserManager<ApplicationUser> _userManager;   //用户管理
        private static RoleManager<ApplicationRole> _roleManager;  // 角色管理
        /// <summary>
        /// 构造函数，负责相关参数的注入和初始化用户管理参数
        /// </summary>
        /// <param name="userManager"></param>
        public SeedData(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;

        }
        /// <summary>
        /// 方法：新增用户
        /// </summary>
        /// <param name="email">邮箱账号</param>
        /// <param name="passWord">账号密码</param>
        /// <param name="role">用户类型</param>
        /// <param name="name">昵称</param>
        private static async Task AddUser(string userName, string passWord, string role, string name)
        {

            var bo = new ApplicationUser()
            {
                UserName = userName,
                Name = name,
            };
            await _userManager.CreateAsync(bo, passWord);
            await _userManager.AddToRoleAsync(bo, role);
        }
        /// <summary>
        /// 方法：新增角色组
        /// </summary>
        /// <param name="roleName">角色组名称</param>
        private static async Task AddRole(string roleName)
        {
            var bo = new ApplicationRole()
            {
                Name = roleName,
            };
            await _roleManager.CreateAsync(bo);
        }
       static List<string> _allRoles = new List<string>()
        {
             "大学生KAB创业俱乐部","Summer Time轮滑社","英语1+1俱乐部", "万维口才协会", "环境保护协会", "电子商务协会", "商务实战协会", "宏源书画社", "CGcat设计联盟", 
             "阳光心理协会", "球联会", "手工艺术协会", "MET音乐协会","会武术协会","FM吉他社电子科技小组", "数学建模协会", "计算机科技协会", "光凌摄影协会", "琅韵读书会", 
             "物流协会", "泷月ACG动漫社", "韵艺协会", "会计理财协会", "天锐工作室", "青年金鹰联盟", "裁判协会","铁甲BAUMA协会", "海渊棋友协会", "F说唱社", "GAO滑板社", 
             "驰美汽车协会",
             "校学生会","电子信息工程学院学生会",
             "Student","Counselor"
        };

        #endregion

        #region 新增任务方法
        private static void CreatTask(CsDbContext db)
        {
            List<Int32> suffix = BigListRandomNumber(1, 300);
            List<string> taskSiteList = new List<string>()
            {
                "博文楼", "竟择楼" ,"体育馆" ,"图书馆" ,"篮球场" ,"田径场" ,"文华楼" ,"天工楼" ,"行政楼" 

            };
            for (int i = 0; i < 3000; i++)
            {
                if (i < 1000)
                {
                    var task = new ApplicationTask()
                    {
                        Name = "活动分活动" +RandomNumber(0, 10)[0] + RandomNumber(0,10)[0]+RandomNumber(0, 10)[0],
                        TaskSites = db.TaskSites.Where(s => s.Name == taskSiteList[RandomNumber(0,taskSiteList.Count-1)[0]]).FirstOrDefault(),
                        Score = RandomNumber(2,10)[0]+"/活动分",
                        BeginTime = DateTime.Parse("2020-"+ RandomNumber(7,12)[0]+"-"+RandomNumber(1,28)[0] + " " + RandomNumber(0, 23)[0] + ":" + RandomNumber(0, 59)[0]),
                        Duration = RandomNumber(1, 10)[0] + "/小时",
                        IssuerID = db.ApplicationRoles.Where(s => s.Name ==_allRoles[RandomNumber(0,_allRoles.Count-1)[0]]).Select(s => s.Id).FirstOrDefault(),
                        ApplicationTaskTypesID = db.ApplicationTaskTypes.Where(s => s.Name == "活动分").Select(s => s.Id).FirstOrDefault(),
                    };
                    db.ApplicationTasks.Add(task);
                }
                if (i>=1000 &&i< 2000)
                {
                    var task = new ApplicationTask()
                    {
                        Name = "义工时活动" + RandomNumber(0, 10)[0] + RandomNumber(0, 10)[0] + RandomNumber(0, 10)[0],
                        TaskSites = db.TaskSites.Where(s => s.Name == taskSiteList[RandomNumber(0, taskSiteList.Count - 1)[0]]).FirstOrDefault(),
                        Score = RandomNumber(1, 10)[0] + "/义工时",
                        BeginTime = DateTime.Parse("2020-" + RandomNumber(7, 12)[0] + "-" + RandomNumber(1, 28)[0] + " " + RandomNumber(0, 23)[0] + ":" + RandomNumber(0, 59)[0]),
                        Duration = RandomNumber(1, 10)[0] + "/小时",
                        IssuerID = db.ApplicationRoles.Where(s => s.Name == _allRoles[RandomNumber(0, _allRoles.Count - 1)[0]]).Select(s => s.Id).FirstOrDefault(),
                        ApplicationTaskTypesID = db.ApplicationTaskTypes.Where(s => s.Name == "义工时").Select(s => s.Id).FirstOrDefault(),
                    };
                    db.ApplicationTasks.Add(task);
                }
                if (i >= 2000 && i < 3000)
                {
                    var task = new ApplicationTask()
                    {
                        Name = "诚信分活动" + RandomNumber(0, 10)[0] + RandomNumber(0, 10)[0] + RandomNumber(0, 10)[0],
                        TaskSites = db.TaskSites.Where(s => s.Name == taskSiteList[RandomNumber(0, taskSiteList.Count - 1)[0]]).FirstOrDefault(),
                        Score = RandomNumber(40, 111)[0] + "/诚信分",
                        BeginTime = DateTime.Parse("2020-" + RandomNumber(7, 12)[0] + "-" + RandomNumber(1, 28)[0] + " " + RandomNumber(0, 23)[0] + ":" + RandomNumber(0, 59)[0]),
                        Duration = RandomNumber(1, 10)[0] + "/小时",
                        IssuerID = db.ApplicationRoles.Where(s => s.Name == _allRoles[RandomNumber(0, _allRoles.Count - 1)[0]]).Select(s => s.Id).FirstOrDefault(),
                        ApplicationTaskTypesID = db.ApplicationTaskTypes.Where(s => s.Name == "诚信分").Select(s => s.Id).FirstOrDefault(),
                    };
                    db.ApplicationTasks.Add(task);
                }

            }
            db.SaveChanges();
        }

        /// <summary>
        /// 创建一个得到随机数数组的方法(方法参数代表随机数范围,生成的数组中含benin,end）
        /// </summary>
        private static List<Int32> RandomNumber(int begin, int end)
        {
            List<Int32> sjList = new List<Int32>();
            for (int i = 0; i < 100; i++)
            {

                byte[] buffer = Guid.NewGuid().ToByteArray();
                int iSeed = BitConverter.ToInt32(buffer, 0);
                Random random = new Random(iSeed);
                sjList.Add(random.Next(begin, end + 1));
            }
            //去除数组重复值
            List<Int32> nlist = sjList;
            for (int i = 0; i < sjList.Count; i++)
            {

                for (int j = sjList.Count - 1; j > i; j--)
                {
                    if (sjList[i] == nlist[j])
                    {
                        sjList.RemoveAt(j);
                    }
                }

            }
            return sjList;
        }

        /// <summary>
        /// 数组元素较多时，创建一个得到随机数数组的方法(方法参数代表随机数范围,生成的数组中含benin,end）
        /// </summary>
        private static List<Int32> BigListRandomNumber(int begin, int end)
        {
            List<Int32> sjList = new List<Int32>();
            for (int i = 0; i < 3000; i++)
            {

                byte[] buffer = Guid.NewGuid().ToByteArray();
                int iSeed = BitConverter.ToInt32(buffer, 0);
                Random random = new Random(iSeed);
                sjList.Add(random.Next(begin, end + 1));
            }
            //去除数组重复值
            List<Int32> nlist = sjList;
            for (int i = 0; i < sjList.Count; i++)
            {

                for (int j = sjList.Count - 1; j > i; j--)
                {
                    if (sjList[i] == nlist[j])
                    {
                        sjList.RemoveAt(j);
                    }
                }

            }
            return sjList;
        }

        #endregion



        public async Task Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new CsDbContext(
                serviceProvider.GetRequiredService<
                    DbContextOptions<CsDbContext>>()))
            {

                //检查角色表是否有数据
                if (context.ApplicationRoles.Any())
                {
                    return;
                }


                #region 创建角色
                for (int i=0; i<_allRoles.Count;i++)
                {
                    await AddRole(_allRoles[i]);
                }
                #endregion

                #region 创建任务地点
                context.TaskSites.AddRange(
                  new TaskSite { Name = "博文楼" },
                  new TaskSite { Name = "竟择楼" },
                  new TaskSite { Name = "体育馆" },
                  new TaskSite { Name = "图书馆" },
                  new TaskSite { Name = "篮球场" },
                  new TaskSite { Name = "田径场" },
                  new TaskSite { Name = "文华楼" },
                  new TaskSite { Name = "天工楼" },
                  new TaskSite { Name = "行政楼" }
                  );
                context.SaveChanges();
                #endregion

                #region 创建任务类型
                context.ApplicationTaskTypes.AddRange(
                  new ApplicationTaskType { Name = "活动分" },
                  new ApplicationTaskType { Name = "义工时" },
                  new ApplicationTaskType { Name = "诚信分" }
                  );
                context.SaveChanges();
                #endregion

                #region 创建任务
                CreatTask(context);
                #endregion

                #region 创建用户

                await AddUser("0@qq.com", "1234@Abcd", "Student", "学生0");
                await AddUser("1@qq.com", "1234@Abcd", "Student", "学生1");
                await AddUser("2@qq.com", "1234@Abcd", "Student", "学生2");
                await AddUser("3@qq.com", "1234@Abcd", "Student", "学生3");
                await AddUser("4@qq.com", "1234@Abcd", "Student", "学生4");
                await AddUser("5@qq.com", "1234@Abcd", "Student", "学生5");
                await AddUser("6@qq.com", "1234@Abcd", "Student", "学生6");
                await AddUser("7@qq.com", "1234@Abcd", "Student", "学生7");
                await AddUser("8@qq.com", "1234@Abcd", "Student", "学生8");
                await AddUser("9@qq.com", "1234@Abcd", "Student", "学生9");
                await AddUser("00@qq.com", "1234@Abcd", "Counselor", "老师0");


                #endregion


            }
        }
    }
}